package cn.wolfcode.car.web.advice;

import cn.wolfcode.car.exception.LoginException;
import cn.wolfcode.car.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class ExceptionControllerAdvice {
    @ExceptionHandler(LoginException.class)
    public String loginException(LoginException e,
                                HandlerMethod handlerMethod,
                                HttpServletResponse response) throws IOException {
        e.printStackTrace();
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            JsonResult jsonResult = new JsonResult(false, e.getMessage());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(jsonResult));
            return null;
        }
        return "common/error";
    }

    @ExceptionHandler(Exception.class)
    public String exceptionAdvice(Exception e,
                                HandlerMethod handlerMethod,
                                HttpServletResponse response) throws IOException {
        e.printStackTrace();
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            JsonResult jsonResult = new JsonResult(false, "系统维护中,请稍后再试");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(jsonResult));
            return null;
        }
        return "common/error";
    }
}
